package com.nowcoder.community.controller;

import ch.qos.logback.core.util.StringUtil;
import com.google.code.kaptcha.Producer;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityContance;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

@Controller
public class LoginController implements CommunityContance {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private UserService userService;
    @Value("${server.servlet.context-path}")
    String pathcontext;
    @Autowired
    private Producer kaptchaProducer;
    @RequestMapping(path = "/login",method = RequestMethod.GET)
    public String getLoginPage() {
        return  "/site/login";
    }
    @RequestMapping(path = "/register",method = RequestMethod.GET)
    public String getRegisterPage() {
        return  "/site/register";
    }

    @RequestMapping(path = "/register", method =RequestMethod.POST)
    public String register(User user, Model model) {
        Map<String, String> map =userService.register(user);
        if (map==null || map.isEmpty()) {
            model.addAttribute("msg","注册成功，我们已发送激活邮件，请尽快激活！");
            model.addAttribute("target","/index");
            return "/site/operate-result";
        } else {
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return "site/register";
        }
    }

    @RequestMapping(path = "/activation/{userId}/{activationCode}",method = RequestMethod.GET)
    public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("activationCode") String code ) {
        int key =userService.activate(userId,code);
        if (key==ACTIVATION_SUCCESS) {
            model.addAttribute("msg","账号激活成功！");
            model.addAttribute("target","/login");
        }else if (key==ACTIVATION_REPEATED) {
            model.addAttribute("msg","不要重复激活！");
            model.addAttribute("target","/index");
        }else{
            model.addAttribute("msg","激活失败！");
            model.addAttribute("target","/index");
        }
        return "/site/operate-result";
    }

    @RequestMapping(path = "/kaptcha",method = RequestMethod.GET)
    public void getKaptcha(HttpSession session, HttpServletResponse response) {
        String text =kaptchaProducer.createText();
        BufferedImage image =kaptchaProducer.createImage(text);
        session.setAttribute("kaptcha",text);
        response.setContentType("image/png");

        try {
            OutputStream os =response.getOutputStream();
            ImageIO.write(image,"png",os);

        } catch (IOException e) {
            logger.error("验证码生成输出失败",e.getMessage());
        }
    }

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public String login(String username, String password, boolean rememberme,
                        HttpSession session,HttpServletResponse response, String code, Model model) {
        String kaptcha =(String) session.getAttribute("kaptcha");
        if (StringUtil.isNullOrEmpty(code) || !kaptcha.equalsIgnoreCase(code)) {
            model.addAttribute("kaptchaMsg","验证码错误");
            return "/site/login";
        }
        int timeout= rememberme?REMEMBER_EXPIRED_SECCOND:DEAFAUT_EXPIRED_SECCOND;
        System.out.println(rememberme);

        Map<String,String> map =userService.login(username,password,timeout);
        if (map.containsKey("ticket")) {
            Cookie cookie=new Cookie("ticket",map.get("ticket"));
            cookie.setMaxAge(timeout);
            cookie.setPath(pathcontext);
            response.addCookie(cookie);
            return "redirect:/index";
        }
        model.addAttribute("usernameMsg",map.get("usernameMsg"));
        model.addAttribute("passwordMsg",map.get("passwordMsg"));
        return "/site/login";
    }

}
